﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using CE.Global;
using CE.TravelInsurance;
using CE.Provider;

public partial class Provider_TravelInsurance_ProviderTIPremium : System.Web.UI.Page
{
    string PageName = "CXTI";
    string SubPageName = "CXTIPRM";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null || Session[CE.Global.General.ProviderCompanyId] == null)
        {
            Response.Redirect("~/Provider/ProviderSecureLogin.aspx");
        }
        CheckMainPageAccess();
        CheckSubPageAccess();

        if (!Page.IsPostBack)
        {
            LoadRegion();
            ClearFields();

            usrEffectivityDate.StartYear = CE.Global.General.GetUTCDateTime().Year;
            usrEffectivityDate.EndYear = CE.Global.General.GetUTCDateTime().Year + 2;

            if (Page.Request.Params["COV"] != null && Page.Request.Params["TID"] != null && Page.Request.Params["PID"] != null )
            {
                string _cover = "";                
                Int64 _pid = 0;              

                Int64.TryParse(Page.Request.Params["PID"], out _pid);
                _cover = Page.Request.Params["COV"].ToString();                

                txtPID.Text = _pid.ToString();
                //ddlLevelOfCoverage.Text = _level;
                ddlPolicyType.Text = _cover;

            }

            if (Page.Request.Params["TID"] != null)
            {
                Int64 _tid = 0;
                Int64.TryParse(Page.Request.Params["TID"], out _tid);
                lblTAId.Text = _tid.ToString();
                ddlPlanName.SelectedValue = _tid.ToString();

                this.GetPlans(this, null);
                this.CheckPremium(this, null);
            }

            ddlPlanName.Items.Insert(0, new ListItem("Select", "-1"));
        }

    }

    private void LoadRegion()
    {
        DataTable _dtRegion = General.GetComboItem("RegionArea", true);
        ddlAreaRegion.DataSource = _dtRegion;
        ddlAreaRegion.DataTextField = _dtRegion.Columns[0].ColumnName.ToString();
        ddlAreaRegion.DataValueField = _dtRegion.Columns[1].ColumnName.ToString();
        ddlAreaRegion.DataBind();

        ddlAreaRegion.Items.Insert(0, new ListItem("Select", "-1"));
    }

    protected void GetPlans(object sender, EventArgs e)
    {
        DataTable dtPlans = new DataTable();
        TAQuoteResultDB _tadb = new TAQuoteResultDB();

        dtPlans = _tadb.GetTASelectSingleItemSelectedDT(Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()), ddlPolicyType.SelectedValue);

        if (dtPlans.Rows.Count > 0)
        {
            ddlPlanName.DataSource = dtPlans;
            ddlPlanName.DataTextField = "PlanName";
            ddlPlanName.DataValueField = "TAInsId";
            ddlPlanName.DataBind();
        }
        else
        {
            ddlPlanName.Items.Clear();
        }

        ddlPlanName.Items.Insert(0, new ListItem("Select", "-1"));

    }

    protected void ibtSubmit_Click(object sender, ImageClickEventArgs e)
    {
        if (Page.IsValid)
        {
            string _authcode = CE.Security.MySecurity.Encrypt(txtAuthCode.Text, true);
            if (CheckAuthCode(_authcode, 600))
            {
                if (ddlPlanName.SelectedIndex > 0)
                {

                    CE.Provider.TAPremiumDB _tapremiumdb = new CE.Provider.TAPremiumDB();
                    CE.Provider.TAPremium _tapremium = new CE.Provider.TAPremium();

                    _tapremium.TAPreId = Convert.ToInt64(txtPID.Text);
                    int _trantype = 1;
                    if (_tapremium.TAPreId > 0)
                    {
                        _trantype = 2;
                    }
                    _tapremium.TAInsId = Convert.ToInt64(lblTAId.Text.ToString());
                    _tapremium.PlanType = ddlPolicyType.SelectedValue.ToString();
                    _tapremium.CoverageLevel = ""; // ddlLevelOfCoverage.SelectedValue.ToString();
                    _tapremium.ProviderCompanyId = Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId]);
                    _tapremium.AreaId = Convert.ToInt64(ddlAreaRegion.SelectedValue.ToString());
                    _tapremium.DurationStart = Convert.ToInt32(txtDurationStart.Text.Trim());
                    _tapremium.DurationEnd = Convert.ToInt32(txtDurationEnd.Text.Trim());
                    _tapremium.Price = float.Parse(txtPrice.Text.Trim());
                    _tapremium.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());

                    if (rdoEffectivity.SelectedValue == "Yes" && usrEffectivityDate.GetDate() > CE.Global.General.GetUTCDateTime())
                    {
                        _tapremium.FInfo1 = float.Parse(txtNewRate.Text);
                        _tapremium.DInfo1 = usrEffectivityDate.GetDate();

                    }
                    else
                    {
                        _tapremium.FInfo1 = float.Parse(txtPrice.Text);
                        _tapremium.DInfo1 = CE.Global.General.GetUTCDateTime();
                    }

                    _tapremium.TAPreId = _tapremiumdb.Insert(_tapremium, ddlPolicyType.SelectedValue.ToString());

                    if (_tapremium.TAPreId > 0)
                    {
                        InsertProviderAuthTransaction(_tapremium.TAPreId, "TIPremium", _trantype, 600, _authcode, _tapremium.ProviderCompanyId, _tapremium.RefCEUserId);
                        ProviderUpdateSave(_tapremium.TAPreId);
                        lblMessage.Text = "Saved successfully!";
                        txtPID.Text = _tapremium.TAPreId.ToString();
                    }
                    else
                    {
                        lblMessage.Text = "Saving failed!";
                    }
                }
                else
                    lblMessage.Text = "Pls. create a plan under this Policy/Coverage level.";

            }
            else
            {
                lblMessage.Text = "Wrong auth code!";
            }
        }

    }

    private void ProviderUpdateSave(Int64 ProviderRefId)
    {
        ProviderUpdates _providerupdates = new ProviderUpdates();
        ProviderUpdatesDB _providerupdatesDB = new ProviderUpdatesDB();

        _providerupdates.UpdateId = 0;
        _providerupdates.CXTableId = GetCXTableId();
        _providerupdates.ProviderRefId = ProviderRefId;

        if (rdoEffectivity.SelectedValue == "Yes" && usrEffectivityDate.GetDate() > CE.Global.General.GetUTCDateTime())
        {
            //Scheduled
            _providerupdates.UpdateType = 1;
        }
        else
        {
            //Immediate
            _providerupdates.UpdateType = 0;
        }

        _providerupdates.ProviderCompanyId = Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId]);
        _providerupdates.RefCEUserID = Convert.ToInt64(Session[General.UserId].ToString());

        _providerupdatesDB.Insert(_providerupdates);

    }

    private Int32 GetCXTableId()
    {
        Int32 CXID = 0;

        ProviderTableListings _tablelist = new ProviderTableListings();
        ProviderTableListingsDB _tablelistdb = new ProviderTableListingsDB();

        int ProviderType = 600; //Travel Insurance
        string CXTable = "tblProviderTAPremium";

        _tablelist = _tablelistdb.GetProviderTableListingsSingleItem(ProviderType, Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId]), CXTable);

        if (_tablelist != null)
            CXID = _tablelist.CXTableId;

        return CXID;

    }

    protected void CheckPremium_SelectedIndexChanged(object sender, EventArgs e)
    {
        ClearFields();
        this.CheckPremium(this, null);
    }

    protected void CheckPremium(object sender, EventArgs e)
    {
        TAQuoteResultDB _tadb = new TAQuoteResultDB();
        TAQuoteResult _tadetails = new TAQuoteResult();

        //_tadetails = _tadb.GetTASelectSingleItemSelected(Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()), ddlPolicyType.SelectedValue.ToString(), ddlLevelOfCoverage.SelectedValue.ToString());
        _tadetails = _tadb.GetTAQuoteResult(Convert.ToInt64(ddlPlanName.SelectedValue), ddlPolicyType.SelectedValue.ToString());

        if (_tadetails != null)
        {
            //lblPlanName.Text = _tadetails.PlanName;
            lblTAId.Text = _tadetails.TAInsId.ToString();
        }

        CE.Provider.TAPremiumDB _tapremiumdb = new CE.Provider.TAPremiumDB();
        DataTable _dtPremium = new DataTable();

        _dtPremium = _tapremiumdb.GetPremiumDTItem(Convert.ToInt64(txtPID.Text), ddlPolicyType.SelectedValue);

        if (_dtPremium.Rows.Count > 0)
        {
            ddlAreaRegion.SelectedValue = _dtPremium.Rows[0]["AreaId"].ToString();
            txtDurationStart.Text = _dtPremium.Rows[0]["DurationStart"].ToString();
            txtDurationEnd.Text = _dtPremium.Rows[0]["DurationEnd"].ToString();
            txtPrice.Text = _dtPremium.Rows[0]["Price"].ToString();

            DateTime dateDinfo1 = CE.Global.General.GetUTCDateTime();
            float Finfo1 = 0;

            if (_dtPremium.Rows[0]["Dinfo1"].ToString() != "" && _dtPremium.Rows[0]["Dinfo1"] != null)
            {
                dateDinfo1 = Convert.ToDateTime(_dtPremium.Rows[0]["Dinfo1"].ToString());
            }

            if (_dtPremium.Rows[0]["Finfo1"].ToString() != "" && _dtPremium.Rows[0]["Finfo1"] != null)
            {
                Finfo1 = float.Parse(_dtPremium.Rows[0]["Finfo1"].ToString());
            }

            if (dateDinfo1 > CE.Global.General.GetUTCDateTime())
            {
                divNewRate.Visible = true;
                txtNewRate.Text = Finfo1.ToString();
                rdoEffectivity.SelectedValue = "Yes";
            }
            else
            {
                divNewRate.Visible = false;
                rdoEffectivity.SelectedValue = "No";
            }

            usrEffectivityDate.Day = dateDinfo1.Day;
            usrEffectivityDate.Month = dateDinfo1.Month;
            usrEffectivityDate.Year = dateDinfo1.Year;

        }
                
    }

    protected void ClearFields()
    {
        //lblPlanName.Text = "";
        txtDurationStart.Text = "";
        txtDurationEnd.Text = "";
        txtPrice.Text = "";
        txtPID.Text = "0";
        lblMessage.Text = "";
        
    }

    protected void ibtBack_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("ViewProviderTIPremium.aspx");
    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        txtDurationStart.Text = "";
        txtDurationEnd.Text = "";
        txtPrice.Text = "";
        txtPID.Text = "0";
        lblMessage.Text = "";
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        rfvAuthCode.Validate();
        if (txtPID.Text != "0" && txtAuthCode.Text.Trim().Length > 0)
        {
            Int64 _providercompanyid = Convert.ToInt64(Session[General.ProviderCompanyId].ToString());
            Int64 _refceuserid = Convert.ToInt64(Session[General.UserId].ToString());
            string _authcode = CE.Security.MySecurity.Encrypt(txtAuthCode.Text, true);

            if (CheckAuthCode(_authcode, 600))
            {
                CE.Provider.TAPremiumDB _tapremiumdb = new CE.Provider.TAPremiumDB();

                _tapremiumdb.Delete(Convert.ToInt64(txtPID.Text));
                InsertProviderAuthTransaction(Convert.ToInt64(txtPID.Text), "TIPremium", 3, 600, _authcode, _providercompanyid, _refceuserid);

                Response.Redirect("ViewProviderTIPremium.aspx");
            }
            else
            {
                lblMessage.Text = "Wrong auth code!";
            }
        }
    }

    public void EffectiveWhen(object sender, EventArgs e)
    {
        if (rdoEffectivity.SelectedValue == "Yes")
        {
            divNewRate.Visible = true;
        }
        else
        {
            divNewRate.Visible = false;
        }

        usrEffectivityDate.Day = CE.Global.General.GetUTCDateTime().Day;
        usrEffectivityDate.Month = CE.Global.General.GetUTCDateTime().Month;
        usrEffectivityDate.Year = CE.Global.General.GetUTCDateTime().Year;
    }

    protected bool CheckAuthCode(string strAuthCode, int intAuthCodeType)
    {
        bool _retValue = false;
        ProviderAuthCode _authcode = new ProviderAuthCode();
        ProviderAuthCodeDB _authcodedb = new ProviderAuthCodeDB();
        _authcode = _authcodedb.GetProviderAuthCode(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()), intAuthCodeType, strAuthCode);
        if (_authcode != null)
        {
            _retValue = true;
        }

        return _retValue;
    }

    protected Int64 InsertProviderAuthTransaction(Int64 TransactionId, string TransactionCode, int TransactionType,
        int AuthCodeType, string AuthCode, Int64 ProviderCompanyId, Int64 RefCEUserId)
    {
        ProviderAuthTransaction _authtrans = new ProviderAuthTransaction();
        ProviderAuthTransactionDB _authtransdb = new ProviderAuthTransactionDB();

        _authtrans.TransactionId = TransactionId;
        _authtrans.TransactionCode = TransactionCode;
        _authtrans.TransactionType = TransactionType;
        _authtrans.AuthCode = AuthCode;
        _authtrans.AuthCodeType = AuthCodeType;
        _authtrans.ProviderCompanyId = ProviderCompanyId;
        _authtrans.RefCEUserID = RefCEUserId;

        _authtrans.AuthTransId = _authtransdb.Insert(_authtrans);
        return _authtrans.AuthTransId;
    }

    private void CheckMainPageAccess()
    {
        Int64 PageAccess = General.GetProviderMainPageAccess(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()),
                                                        Convert.ToInt64(Session[General.UserId].ToString()), PageName);
        if (PageAccess == 0)
        {
            //Response.Redirect("~/Provider/UserMessage.aspx?errorcode=2000");
            Response.Redirect("~/Provider/UserMessage.aspx?mt=UM&ec=2000");
        }
    }

    private void CheckSubPageAccess()
    {
        Int64 PageAccess = General.GetProviderSubPageAccess(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()),
                                                        Convert.ToInt64(Session[General.UserId].ToString()), SubPageName);
        if (PageAccess == 0)
        {
            //Response.Redirect("~/Provider/UserMessage.aspx?errorcode=2000");
            Response.Redirect("~/Provider/UserMessage.aspx?mt=UM&ec=2000");
        }
        else if (PageAccess == 100)
        {
            ibtSubmit.Enabled = false;
            btnNew.Enabled = false;
            btnDelete.Enabled = false;
        }
        else if (PageAccess == 200)
        {
            ibtSubmit.Enabled = true;
            btnNew.Enabled = true;
            btnDelete.Enabled = false;
        }
        else if (PageAccess == 300)
        {
            ibtSubmit.Enabled = true;
            btnNew.Enabled = true;
            btnDelete.Enabled = true;
        }
    }

}
